<template>
  <view class="search-page">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-wrap">
        <image src="/static/index/union.png" mode="widthFix" class="search-icon"></image>
        <input type="text" v-model="query.keyword" class="search-input" placeholder="请输入搜索内容"
          placeholder-class="placeholder" @confirm="handleSearch" confirm-type="search" focus />
        <view class="clear-icon" @click="toCode">
          <image src="/static/index/scode.png" mode="widthFix" class="search-icon"></image>
        </view>
      </view>
      <view class="cancel-btn" @click="goBack">取消</view>
    </view>

    <!-- 历史搜索列表 -->
    <view class="history-search" v-if="historySearchList.length &&!hasSearched">
      <view class="history-search-item-top">
        <view class="history-search-item-top-title">历史搜索</view>
        <view class="history-search-item-top-clear" @click="clearHistory">
          <image src="/static/index/del.png" mode="widthFix" class="del-icon"></image>
        </view>
      </view>
      <view class="history-search-item">
        <view class="history-search-item-text" @click="handleClickHistory(item)"
          v-for="(item, index) in historySearchList" :key="index">{{item}}
        </view>
      </view>
    </view>

    <view class="medicine-list">
      <view class="list-content">
        <view class="list-item"
          :class="{'success': Number(item.inventory) - Number(item.threshold) > 0, 'warning': Number(item.inventory) - Number(item.threshold) <= 0, 'danger': Number(item.inventory) == 0}"
          v-for="item in dataList" :key="item.id" @click="handleSelect(item)">
          <view class="item-bottom">
            <view class="item-bottom-left"
              :class="{'success': Number(item.inventory) - Number(item.threshold) > 0, 'warning': Number(item.inventory) - Number(item.threshold) <= 0, 'danger': Number(item.inventory) == 0}">
              {{ item.slotName || '' }}
            </view>
          </view>
          <view class="item-name">{{ item.medicineName || '-' }}</view>
          <view class="item-cell">{{ item.barCode || '-' }}</view>
          <view class="item-cell">{{ item.manufacturer || '-' }}</view>
          <view class="item-num"
            :class="{'success': Number(item.inventory) - Number(item.threshold) > 0, 'warning': Number(item.inventory) - Number(item.threshold) <= 0, 'danger': Number(item.inventory) == 0}">
            库存数量: {{ item.inventory||0 }}</view>

        </view>
      </view>
    </view>
    <!-- 无搜索结果 -->
    <view class="empty-result" v-if="!dataList.length && hasSearched">
      <image src="/static/images/empty-search.png" mode="aspectFit" class="empty-icon"></image>
      <view class="empty-text">暂无相关商品</view>
    </view>
    <out-channel ref="outDialogs" :medicineInfo="medicineInfo" @getSupply="handleSearch" />
    <medicine-dialogs ref="medicineDialogs" :medicineInfo="medicineInfo" @getSupply="handleSearch" />
  </view>
</template>

<script setup>
  import { ref, watch } from 'vue'
  import { onLoad, onReachBottom } from '@dcloudio/uni-app'
  import { getSlotRight } from '@/api/storeManage.js'
  import medicine from '@/components/medicine/index.vue'
  import outChannel from '@/components/outChannel/index.vue'
  import MedicineDialogs from '@/components/medicineDialogs/index.vue'
  const hasSearched = ref(false)
  const query = ref({
    keyword: '',
    pageNum: 1,
    pageSize: 10,
    cabinetId: uni.getStorageSync('machineInfo').id
  })
  const dataList = ref([])
  const historySearchList = ref([])
  const type = ref(0)
  const outDialogs = ref(null)
  const medicineInfo = ref({})
  const medicineDialogs = ref(null)
  const status = ref('loadmore')
  const total = ref(0)

  // 获取货架列表
  const getList = async () => {
    try {
      const res = await getSlotRight(query.value)
      if (res.code == 200) {
        dataList.value = query.value.pageNum === 1 ? res.rows : dataList.value.concat(res.rows)
        total.value = res.total || 0
        dataList.value = dataList.value.map(item => {
          return {
            ...item,
            status: Number(item.inventory) == 0 ? 'danger' : Number(item.inventory) - Number(item.threshold) > 0 ? 'success' : 'warning'
          }
        })
        status.value = dataList.value.length >= total.value ? 'nomore' : 'loadmore'
      }
    } catch (error) {
      console.log(error)
    }
  }

  onLoad((options) => {
    type.value = options.type || 0
    // 当类型改变时，清除历史搜索记录
    if (type.value == 0) {
      historySearchList.value = uni.getStorageSync('historySearchList1') || []
    } else {
      historySearchList.value = uni.getStorageSync('historySearchList2') || []
    }
  })
  watch(query.value, (newVal) => {
    if (newVal.keyword == '') {
      hasSearched.value = false
    }
  }, {
    immediate: true,
    deep: true
  })
  const handleClickHistory = (name) => {
    query.value.keyword = name
    hasSearched.value = true
    getList()
  }
  // 处理搜索
  const handleSearch = () => {
    hasSearched.value = true
    console.log(!historySearchList.value.includes(query.value.keyword), '---------------udes(query.value.keyword)')
    if (query.value.keyword != "" && !historySearchList.value.includes(query.value.keyword)) {
      historySearchList.value.unshift(query.value.keyword)
    }
    if (historySearchList.value.length > 10) {
      historySearchList.value.pop()
    }
    if (type.value == 0) {
      uni.setStorageSync('historySearchList1', historySearchList.value)
    } else {
      uni.setStorageSync('historySearchList2', historySearchList.value)
    }

    getList()
    // TODO: 实现搜索逻辑
  }

  const toCode = () => {
    uni.scanCode({
      scanType: ['barCode', 'qrCode'],
      success: (res) => {
        query.value.keyword = res.result
      },
      fail: (err) => {
        uni.showToast({
          title: '扫码失败，请重试',
          icon: 'none'
        })
      }
    })
    // query.value.keyword = ''
    // hasSearched.value = false
    // historySearchList.value = []
  }



  // 返回上一页
  const goBack = () => {
    uni.navigateBack()
  }

  // 选择商品
  const handleSelect = (item) => {
    console.log(item, 'item', type.value)
    medicineInfo.value = item
    if (type.value == 1) {
      outDialogs.value.openStockDialog()
    } else {
      medicineDialogs.value.openStockDialog()
    }
  }


  // 清空历史搜索
  const clearHistory = () => {
    uni.showModal({
      title: '提示',
      content: '确定要清空历史搜索吗？',
      success: (res) => {
        if (res.confirm) {
          historySearchList.value = []
          if (type.value == 0) {
            uni.removeStorageSync('historySearchList1')
          } else {
            uni.removeStorageSync('historySearchList2')
          }

        }
      }
    })
  }

  onReachBottom(() => {
    if (dataList.value.length < total.value) {
      query.value.pageNum++;
      getList();
    }
  });
</script>

<style lang="scss" scoped>
  .medicine-list {
    .list-content {
      padding: 10rpx;
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .list-item {
        width: 280rpx;
        display: flex;
        padding: 18rpx 30rpx;
        background: #fff;
        border-radius: 16rpx;
        margin-bottom: 20rpx;
        flex-direction: column;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        margin: 12rpx;

        &.success {
          background-image: url('/static/index/box_1.png');
        }

        &.warning {
          background-image: url('/static/index/box_2.png');
        }

        &.danger {
          background-image: url('/static/index/box_3.png');
        }

        .item-cell {
          font-size: 26rpx;
          color: #999;
          margin-bottom: 12rpx;

          &:nth-child(1) {
            font-size: 28rpx;
            margin-bottom: 14rpx;
            font-weight: 600;
            color: #000;
          }
        }

        .item-name {
          font-size: 27rpx;
          margin-bottom: 14rpx;
          margin-top: 14rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-weight: 600;
          color: #000;
        }

        .item-num {
          border-bottom: 1rpx solid #f5f5f5;
          padding-bottom: 12rpx;
          font-size: 26rpx;

          &.success {
            color: #07c160;
          }

          &.warning {
            color: #ff9900;
          }

          &.danger {
            color: #ff4d4f;
          }
        }

        .item-bottom {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 24rpx;
          color: #999;
          margin: 10rpx 0 12rpx;

          .item-bottom-left {
            font-size: 26rpx;
            padding: 8rpx 20rpx;
            color: #fff;
            border-radius: 30rpx;

            &.success {
              background: #07c160;
            }

            &.warning {
              background: #ff9900;
            }

            &.danger {
              background: #ff4d4f;
            }
          }

          .item-bottom-right {
            font-size: 26rpx;
            padding: 16rpx 64rpx;
            color: #fff;
            background: #3B82F6;
            border-radius: 60rpx;
          }
        }
      }

      .empty-state {
        padding: 100rpx 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;
        font-size: 28rpx;

        image {
          width: 200rpx;
          height: 200rpx;
          margin-bottom: 20rpx;
        }
      }
    }
  }

  .search-page {
    min-height: 100vh;
    background: #f5f5f5;

    .search-header {
      display: flex;
      align-items: center;
      padding: 106rpx 30rpx 16rpx;
      background: #fff;
      border-bottom: 1rpx solid #f5f5f5;

      .search-input-wrap {
        flex: 1;
        height: 64rpx;
        background: #f7f7f7;
        border-radius: 32rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        margin-right: 20rpx;

        .search-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 12rpx;
        }

        .search-input {
          flex: 1;
          height: 100%;
          font-size: 26rpx;
        }

        .placeholder {
          color: #999;
          font-size: 26rpx;
        }

        .clear-icon {
          width: 36rpx;
          height: 36rpx;
          color: #999;
        }
      }

      .cancel-btn {
        font-size: 26rpx;
        color: #3B82F6;
        padding: 0 4rpx;
      }
    }

    .search-result {
      height: calc(100vh - 97rpx);

      .result-item {
        display: flex;
        padding: 24rpx 30rpx;
        background: #fff;
        border-bottom: 1rpx solid #f5f5f5;

        .aisle-tag {
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          font-size: 22rpx;
          color: #fff;
          height: fit-content;
          margin-right: 16rpx;
          min-width: 70rpx;
          text-align: center;

          &.success {
            background: #07c160;
          }

          &.warning {
            background: #ff9900;
          }

          &.danger {
            background: #ff4d4f;
          }
        }

        .item-info {
          flex: 1;

          .product-name {
            font-size: 26rpx;
            color: #333;
            margin-bottom: 8rpx;
            line-height: 1.4;
          }

          .product-code {
            font-size: 22rpx;
            color: #999;
            margin-bottom: 8rpx;
            line-height: 1.4;
          }

          .stock-info {
            font-size: 22rpx;
            line-height: 1.4;

            &.success {
              color: #07c160;
            }

            &.warning {
              color: #ff9900;
            }

            &.danger {
              color: #ff4d4f;
            }
          }
        }
      }
    }

    .history-search {
      background: #fff;
      height: 100vh;
      padding: 0 30rpx 20rpx;

      .del-icon {
        width: 26rpx;
        height: 26rpx;
      }

      .history-search-item-top {
        padding: 0 20rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .history-search-item-top-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #3D3D3D;
        }

        .history-search-item-top-clear {
          font-size: 26rpx;
          color: #333;
        }
      }

      .history-search-item {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;

        .history-search-item-text {
          font-size: 26rpx;
          color: #6B7280;
          margin: 10rpx;
          background-color: #f5f5f5;
          padding: 10rpx 24rpx;
          border-radius: 30rpx;
        }
      }
    }

    .empty-result {
      padding-top: 200rpx;
      text-align: center;

      .empty-icon {
        width: 180rpx;
        height: 180rpx;
        margin-bottom: 16rpx;
      }

      .empty-text {
        font-size: 26rpx;
        color: #999;
      }
    }
  }
</style>